import { ref } from "vue";

export const useAduio = () => {
	const current = ref(0);
	const duration = ref(0);

	const audio = uni.createInnerAudioContext();

	const setSrc = (src) => {
		audio.src = src;
		current.value = 0;
		duration.value = 0;
		audio.play();
	};

	audio.onCanplay(() => {
		duration.value = audio.duration;
	});

	audio.onTimeUpdate(() => {
		current.value = audio.currentTime;
	});

	audio.onError((e) => {
		uni.showToast({
			title: e || "加载失败，请切换歌曲",
			icon: "error",
			mask: true,
			fail: () => {
				audio.stop();
			},
		});
	});

	return { duration, current, audio, setSrc };
};
